#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/time.h>

#include "NodeService.h"
#include "NodeService_server.h"
#include "NodeService_client.h"

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::thrift::server;

using boost::shared_ptr;
using namespace boost;
using namespace  mp2;

/**
 * Creates a client object for a given port,
 * so that functions may then be called on
 * that remote object.
 * @param info Node to create the object from.
 */
NodeClient::NodeClient(NodeInfo info)
{
	if(info.port <= 0)
	{
		//Don't attempt to connect to an incorrect port
		//return;
	}
	shared_ptr<TTransport> socket(new TSocket("localhost", info.port));
	shared_ptr<TTransport> transport(new TBufferedTransport(socket));
	i_transport = transport;
	shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
	client = new NodeServiceClient(protocol);

	i_transport->open();
}

/**
 * Closes our client so that the request finishes.
 */
NodeClient::~NodeClient()
{
	i_transport->close();
}